package com.haitao.jt808.entity.gpsdata;

import com.haitao.jt808.util.Jt808Constant;
import com.haitao.jt808.util.Jt808Util;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;
import lombok.Data;
import org.springframework.beans.BeanUtils;

/**
 * @author: shenhaitao
 * @Description: 平台通用应答
 * @Version: 1.0
 */
@Data
public class Data0x8100 extends DataPackage {

    /**
     * 成功/确认
     */
    public static final byte SUCCESS = 0;

    /**
     * 失败
     */
    public static final byte FAILURE = 1;

    /**
     * 消息有误
     */
    public static final byte MSG_ERROR = 2;

    /**
     * 不支持
     */
    public static final byte UNSUPPORTED = 3;

    /**
     * 报警处理确认
     */
    public static final byte ALARM_PROCESS_ACK = 4;

    public static Data0x8100 response(DataPackage msg, int flowId, byte result) {
        System.out.println("sadasda: "+ ByteBufUtil.hexDump(msg.getMsgBody()));
        if (result != SUCCESS && result != FAILURE && result != MSG_ERROR && result != UNSUPPORTED && result != ALARM_PROCESS_ACK) {
            throw new RuntimeException("传入的result有误");
        }
        Data0x8100 resp = new Data0x8100();
        Header header = msg.getHeader();
        Header respHeader = resp.getHeader();
        BeanUtils.copyProperties(header, respHeader);
        //设置消息ID
        respHeader.setMsgId(Jt808Constant.终端注册应答);
        //设置消息流水号
        respHeader.setFlowId(flowId);
        ByteBuf byteBuf;
        if (header.isVersion2019()) {
            //封装返回的信息
            //2019年协议终端手机号为10个字节
            byteBuf = ByteBufAllocator.DEFAULT.heapBuffer(15);
        } else {
            //封装返回的信息
            //2011、2013年协议终端手机号为6个字节
            byteBuf = ByteBufAllocator.DEFAULT.heapBuffer(11);
        }
        //应答ID(2个字节)对应的终端消息的ID
        byteBuf.writeShort(header.getMsgId());
        //应答流水号(2个字节)对应的终端消息的流水号
        byteBuf.writeShort(header.getFlowId());
        byteBuf.writeByte(result);
        //2019年协议终端手机号为10个字节
        String terminalPhone = header.getTerminalPhone();
        byte[] bytes = Jt808Util.toBcdBytes(terminalPhone);
        byteBuf.writeBytes(bytes);
        //设置返回的消息
        resp.setMsgBody(byteBuf);
        return resp;
    }

}
